package com.fancon.android.gardenjokesx.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.TextView;

import com.fancon.android.emoji.widget.RichTextView;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.adapter.JokesAdapter;
import com.fancon.android.gardenjokesx.dialog.UserReportingDialog;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.PhotoJson;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.gardenjokesx.widget.ProfileDetailHeaderView;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;
import com.fancon.android.ui.widget.ImageCacheView;

/**
 * Detail profile user
 * 
 * @author binhbt
 * 
 */
public class ProfileActivity extends GardenJokesBaseActivity {
	private int index = 1;
	private View footerView, header;
	private ListView mList;
	private Boolean isFirst = true;
	private boolean loadingMore = false;
	private ArrayList<Photo> listPhotos = new ArrayList<Photo>();
	private Boolean isEnd = false;
	private JokesAdapter adapter = null;
	//
	private String currentUserId;
	private Boolean isAuth = false;
	private String mViewedUserId;
	private User user;
	public Boolean isBlocked = false;
	private RichTextView name;
	private TextView username;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile_layout);

		//
		Bundle extras = getIntent().getExtras();
		User userx = UserUtil.getInfoUserLogin(getApplicationContext());
		currentUserId = userx.getUser_id();
		mViewedUserId = currentUserId;
		if (extras != null) {
			mViewedUserId = extras.getString(Constant.USER_ID_VIEW);
		}
		
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		footerView = layoutInflater.inflate(R.layout.listfooter, null, false);
		header = new ProfileDetailHeaderView(this);
		View moreBtn = findViewById(R.id.action_bar_button_more);
		name = (RichTextView)findViewById(R.id.action_bar_textview_title_name);
		username = (TextView)findViewById(R.id.action_bar_textview_title_username);
		moreBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isAuth) {
					Intent intent = new Intent(ProfileActivity.this,
							ProfileSettingActivity.class);
					startActivity(intent);
				} else {
					Dialog userReport = new UserReportingDialog(
							ProfileActivity.this, mViewedUserId, isBlocked);
					userReport.show();
				}
			}
		});
		View backBtn = findViewById(R.id.action_bar_button_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		mList = (ListView) findViewById(R.id.lst_id);
		mList.addHeaderView(header);

		mList.addFooterView(footerView);

		mList.setCacheColorHint(0);
		mList.setOnScrollListener(new OnScrollListener() {

			// useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			// dumdumdum
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				// what is the bottom iten that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;

				// is the bottom item visible & not loading more already ? Load
				// more !
				if ((lastInScreen == totalItemCount) && !(loadingMore)
						&& (!isEnd) && (!isFirst)) {
					loadMore();
				}
			}
		});
		// Load user profile
		UserProfileRequest userRequest = new UserProfileRequest("user_profile",
				this);
		getGlobalState().getRequestQueue().addRequest(userRequest);
		//load empty data
		ArrayList<Photo> tmp = new ArrayList<Photo>();
		adapter = new JokesAdapter(this, tmp);
		mList.setAdapter(adapter);
		// Load user data
		load();

		// init config
		initConfig();
	}

	public void loadMore() {
		footerView.setVisibility(View.VISIBLE);
		index++;
		load();
	}

	public void load() {
		JokesRequest photoReq = new JokesRequest("photo_rq", this);
		getGlobalState().getRequestQueue().addRequest(photoReq);
	}

	private void loadDataView() {
		if (adapter == null||isFirst) {
			adapter = new JokesAdapter(this, listPhotos);
			mList.setAdapter(adapter);
		} else {
			adapter.setLisPhoto(listPhotos);
			adapter.notifyDataSetChanged();
			Log.d("Profile adapter changed", "Profile adapter changed");
		}
	}

	class JokesRequest extends RequestUI {
		private Activity context;
		private FanconProgressBar progress;
		private ArrayList<Photo> tmp;

		public JokesRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			loadingMore = true;
			context = activity;
			if (isFirst) {
				progress = FanconProgressBar.show(context,
						context.getString(R.string.loading));
			}
		}

		@Override
		public void execute() throws Exception {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs
					.add(new BasicNameValuePair("user_id", currentUserId));
			nameValuePairs.add(new BasicNameValuePair("viewed_id",
					mViewedUserId));
			nameValuePairs.add(new BasicNameValuePair("page_index", String.valueOf(index)));
			GardenJokesApiConnect api = new GardenJokesApiConnect(context);
			String result = api.execGet(getApplicationContext(),
					GardenJokesApiConnect.GROUP_M, "getListPhotoDetailOfUser", nameValuePairs);
			Log.v("StringResult", result);
			JsonPaser jP = new JsonPaser();
			// listPhoto = jP.getListPhoto(result);
			tmp = jP.getListPhotoDetail(result);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			footerView.setVisibility(View.GONE);
			try {
				if (tmp.size() > 0) {
					if (listPhotos.size() > 0 && !isFirst) {
						listPhotos.addAll(tmp);
					} else {
						listPhotos = tmp;
					}
				}
				if (tmp.size() == 0) {
					isEnd = true;
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				isEnd = true;
			}
			loadDataView();
			loadingMore = false;
			isFirst = false;
			if (progress != null) {
				progress.dismiss();
			}
		}

	}

	class CommentAdapter extends BaseAdapter implements Filterable {
		private LayoutInflater mInflater;
		private ArrayList<PhotoJson> lisPhoto;

		public CommentAdapter(Context context, ArrayList<PhotoJson> lisPhoto) {
			mInflater = LayoutInflater.from(context);
			this.lisPhoto = lisPhoto;
		}

		public ArrayList<PhotoJson> getLisPhoto() {
			return lisPhoto;
		}

		public void setLisPhoto(ArrayList<PhotoJson> lisPhoto) {
			this.lisPhoto = lisPhoto;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			int ret = lisPhoto.size();
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.row_user, null);
				holder = new ViewHolder();
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return convertView;
		}


		@Override
		public Filter getFilter() {
			// TODO Auto-generated method stub
			return null;
		}

		class ViewHolder {
			ImageCacheView thumb;
			ImageCacheView thumb1;
		}
	}

	class UserProfileRequest extends RequestUI {

		public UserProfileRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			if (isFirst) {
			}
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs
					.add(new BasicNameValuePair("user_id", currentUserId));
			nameValuePairs.add(new BasicNameValuePair("viewed_user_id",
					mViewedUserId));
			GardenJokesApiConnect api = new GardenJokesApiConnect(
					ProfileActivity.this);
			String result = api.getApiData(getApplicationContext(),
					GardenJokesApiConnect.GROUP_M, "getUserViewDetail",
					nameValuePairs);
			Log.v("StringResult", result);
			JsonPaser jP = new JsonPaser();
			user = jP.getUser(result);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			loadUserProfile();
			isFirst = false;
		}
	}

	private void loadUserProfile() {
		try {
			if (user != null) {
				isBlocked = user.isIs_blocked();
				((ProfileDetailHeaderView) header).loadUserProfile(user,
						currentUserId, mViewedUserId);
				name.setText(StringUtil.getDisplayName(user.getLast_name(), user.getFirst_name(), user.getUser_name()));
				username.setText(user.getUser_name());
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	private void initConfig() {
		this.isAuth = currentUserId.equals(mViewedUserId) ? true : false;
	}
	public void setIsBlocked(Boolean block) {
		this.isBlocked = block;
	}
}
